#ifndef INET_ACCEPTOR_H
#define INET_ACCEPTOR_H

#include "Handle.h"
#include "Reactor.h"
#include "InetAddress.h"
#include "EventHandler.h"
#include "EventTypes.h"
#include "SocketAcceptor.h"
#include "SocketStream.h"
#include "InetAddress.h"
#include "Buffer.h"
#include "EchoServiceHandler.h"

template <class SERVICE_HANDLER>

class Acceptor : public EventHandler {
public:
  Acceptor (InetAddress &localAddr, Reactor *reactor, Buffer * buf)
    : reactor_(reactor), buf_(buf)
  {
    peerAcceptor_ = new SocketAcceptor(localAddr);
    reactor_->registerHandler(this, ACCEPT_EVENT);
  }

  virtual void accept ()
  {
    SERVICE_HANDLER *serviceHandler = makeServiceHandler();
    acceptServiceHandler(serviceHandler);
    activateServiceHandler(serviceHandler);
  }
  
protected:
  virtual SERVICE_HANDLER *makeServiceHandler ()
  {
    return new SERVICE_HANDLER(reactor_,buf_);
  }
  
  virtual void acceptServiceHandler(SERVICE_HANDLER *sh)
  {
    peerAcceptor_->accept(sh->peer());
  }
  
  virtual void activateServiceHandler(SERVICE_HANDLER *sh)
  {
    /* skal vi setHanlde?? */
    sh->open();
  }
  
  virtual Handle getHandle ()
  {
    return peerAcceptor_->getHandle();
  }
  
  virtual void handleEvent (Handle h, EventType et)
  {
    if (et == ACCEPT_EVENT)
      accept();
  }
  
private:
  Buffer * buf_;
  SocketAcceptor *peerAcceptor_;
  Reactor *reactor_;
};

#endif
